﻿using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Models;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.AppointAPI.Ganzhou;
using Azure;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using DocumentFormat.OpenXml.Vml;
using FluentFTP;
using Masuit.Tools;
using MaterialDesignThemes.Wpf;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using Prism.Ioc;
using System.Text;
using System.Web;

namespace AJWPFAdmin.Services.AppointAPI
{
    public class GanzhouAppointAPI : AppointAPIBase
    {
        private APIConfig _apiConfig;
        private IGanzhouApiImplement _ganzhouApiImplement;

        public GanzhouAppointAPI(ApplicationType appType,
            SystemConfigDictionary cfg,
            IContainerProvider svcProvider) : base(appType, cfg, svcProvider)
        {
            if (svcProvider.IsRegistered<IGanzhouApiImplement>())
            {
                _ganzhouApiImplement = svcProvider.Resolve<IGanzhouApiImplement>();
            }
        }

        protected override void OnAPILogsRaised(PassagewayDirection? direction,
            string logs)
        {
            base.OnAPILogsRaised(direction, logs);
        }

        public override Task<ProcessResult> UploadCarInfoAsync(CarInfoParams @params)
        {
            return Task.FromResult(ProcessResult.DefaultSuccess);
        }

        public override async Task<ProcessResult> UploadComanyInfoAsync(string @params)
        {
            var result = new ProcessResult();
            try
            {
                var req = CommonUtil.TryGetJSONObject<GanzhouUploadComanyInfoReq>(@params);
                if (req == default)
                {
                    result.SetError("req is null");
                    _logger.Error($"GanzhouAppointAPI--UploadComanyInfoAsync error: req is null");
                }
                var reqs = new List<GanzhouUploadComanyInfoReq> { req };
                var res = await _ganzhouApiImplement.PostComanyInfo(reqs);
                if (res.Code == "200")
                {
                    result.SetSuccess();
                    _logger.Info($"GanzhouAppointAPI--UploadComanyInfoAsync-success-赣州市-上传门禁企业信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"GanzhouAppointAPI--UploadComanyInfoAsync error: {res.Msg}");
                }
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"GanzhouAppointAPI--UploadComanyInfoAsync error: {ex.Message}");
            }

            return result;
        }

        public override async Task<ProcessResult> UploadDeviceInfoAsync(DeviceInfoParams @params)
        {
            var result = new ProcessResult();
            try
            {
                if (@params.Device.Type >= DeviceType.高频读头)
                {
                    result.SetSuccess();
                    return result;
                }
                if (@params.Operation == DataOperationType.移除)
                {
                    result.SetSuccess();
                    return result;
                }

                var req = new GanzhouUploadDeviceInfoReq
                {
                    jksbbm = @params.Device.Code,
                    jksbmc = @params.Device.Name,
                    sscs = _apiConfig.companyname,
                };
                var reqs = new List<GanzhouUploadDeviceInfoReq> { req };
                var res = await _ganzhouApiImplement.PostDeviceInfo(reqs);
                if (res.Code == "200")
                {
                    result.SetSuccess();
                    _logger.Info($"GanzhouAppointAPI--UploadDeviceInfoAsync-success-赣州市-上传门禁监控设备信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"GanzhouAppointAPI--UploadDeviceInfoAsync error: {res.Msg}");
                }
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"GanzhouAppointAPI--UploadDeviceInfoAsync error: {ex.Message}");
            }
            return result;
        }

        public override async Task<ProcessResult> UploadShippingRecordAsync(ShippingRecordParams @params)
        {
            var result = new ProcessResult();
            try
            {
                var req = new GanzhouUploadShippingRecordInfoReq
                {
                    cjjgbm = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.DeviceCode : @params.Record.OutDeviceCode,
                    cjjgmc = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.DeviceCode : @params.Record.OutDeviceCode,
                    srsj = @params.Record.Direction == PassagewayDirection.进
                                    ? @params.Record.ShipStartDate.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss")
                                    : @params.Record.ShipEndDate.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss"),
                    cph = @params.Record.CarNo,
                    cpcolor = ((byte)@params.Record.PlateColor).ToString(),
                    cllx = @params.Record.TypeName,
                    pfjd = @params.Record.EmissionStandard.ToString(),
                    rlzl = @params.Record.FuelTypeName,
                    jlbh = @params.Record.Id.ToString(),
                };
                var reqs = new List<GanzhouUploadShippingRecordInfoReq> { req };
                var res = await _ganzhouApiImplement.PostShippingRecordInfo(reqs);
                if (res.Code == "200")
                {
                    result.SetSuccess();
                    _logger.Info($"GanzhouAppointAPI--UploadShippingRecordAsync-success-赣州市-门禁过车信息成功!");

                    var (_, plate, carTail) = @params.Record.GetWatchPositionImageFile(@params.Record.Direction);

                    var carNo = @params.Record.CarNo;

                    plate = _carIdentificationConfig.CompleteFileUrl(carNo, plate);
                    carTail = _carIdentificationConfig.CompleteFileUrl(carNo, carTail);

                    var yearMonthDay = DateTime.Now.ToString("yyyy/MM/dd");
                    var hourMinuteSecond = DateTime.Now.ToString("HHmmss");
                    var destPathPlate = $"/qymj/{yearMonthDay}/{@params.Record.Id.ToString()}_cpzt_{hourMinuteSecond}.jpg";
                    var destPathTail = $"/qymj/{yearMonthDay}/{@params.Record.Id.ToString()}_cszt_{hourMinuteSecond}.jpg";
                    var ftpOptions = new FtpOptions
                    {
                        Host = _apiConfig.ftpUrl,
                        Port = _apiConfig.ftpPort.ToInt32(),
                        User = _apiConfig.ftpusername,
                        Password = _apiConfig.ftppassword,
                    };
                    AsyncFtpClient ftpClient = null;
                    try
                    {
                        ftpClient = await FtpUtil.GetAsyncFtpClient(ftpOptions);
                        //var plate = "F:\\1.png";
                        if (File.Exists(plate))
                        {
                            await ftpClient.UploadFile(plate, destPathPlate, createRemoteDir: true);
                            _logger.Info($"GanzhouAppointAPI--UploadFile-plate-success-赣州市-门禁车牌号图片上传成功!");
                        }
                        else
                        {
                            _logger.Error($"GanzhouAppointAPI--UploadFile-plate-fail-赣州市-门禁车牌图片上传失败，原因：本地车牌图片路径:{plate}不存在!");
                        }
                        //var carTail = "F:\\1.png";
                        if (File.Exists(carTail))
                        {
                            await ftpClient.UploadFile(carTail, destPathTail, createRemoteDir: true);
                            _logger.Info($"GanzhouAppointAPI--UploadFile-plate-success-赣州市-门禁车身图片上传成功!");
                        }
                        else
                        {
                            _logger.Error($"GanzhouAppointAPI--UploadFile-plate-fail-赣州市-门禁车身图片上传失败，原因：本地车身图片路径:{carTail}不存在!");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"GanzhouAppointAPI--UploadFile-plate-fail-赣州市-门禁车身+车牌图片上传失败，原因：上传Ftp时异常{ex.Message}!");
                    }
                    finally
                    {
                        if (ftpClient.IsConnected)
                        {
                            //关闭
                            await ftpClient.Disconnect();
                            ftpClient.Dispose();
                        }
                    }
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"GanzhouAppointAPI--UploadShippingRecordAsync error: {res.Msg}");
                }
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"GanzhouAppointAPI--UploadShippingRecordAsync error: {ex.Message}");
            }

            return result;
        }

        public override Task ConvertToCustomConfig(bool isReal)
        {
            _apiConfig = CommonUtil.TryGetJSONObject<APIConfig>(Config.StringValue) ?? new APIConfig();
            _customAPIConfig = _apiConfig;
            AutoUploadDataVerification = _apiConfig.AutoUploadDataVerification;

            if (isReal)
            {

            }
            else
            {
                _ = GetSchemas();
            }

            return Task.CompletedTask;
        }

        public new void Dispose()
        {

        }

        public class APIConfig : APIConfigBase
        {
            [DynamicFormItemDefine("接口地址")]
            public string url { get; set; }
            [DynamicFormItemDefine("接口用户名")]
            public string username { get; set; }

            [DynamicFormItemDefine("接口密码")]
            public string password { get; set; }

            [DynamicFormItemDefine("文件上传地址")]
            public string ftpUrl { get; set; }
            [DynamicFormItemDefine("文件上传端口号")]
            public string ftpPort { get; set; }

            [DynamicFormItemDefine("文件上传用户名")]
            public string ftpusername { get; set; }

            [DynamicFormItemDefine("文件上传密码")]
            public string ftppassword { get; set; }

            [DynamicFormItemDefine("企业名称")]
            public string companyname { get; set; }

            [DynamicFormItemDefine("企业简称")]
            public string companyjc { get; set; }

            [DynamicFormItemDefine("企业编码")]
            public string companycode { get; set; }

            [DynamicFormItemDefine("统一信用代码")]
            public string unifiedcreditcode { get; set; }

            [DynamicFormItemDefine("法人代表")]
            public string corpname { get; set; }

            [DynamicFormItemDefine("行业类型编码")]
            public string industrytypecode { get; set; }

            [DynamicFormItemDefine("行业类型名称")]
            public string industrytypename { get; set; }
            [DynamicFormItemDefine("企业地址")]
            public string address { get; set; }
            [DynamicFormItemDefine("区县编码")]
            public string countycode { get; set; }
            [DynamicFormItemDefine("区县名称")]
            public string countyname { get; set; }
            [DynamicFormItemDefine("产能")]
            public string cn { get; set; }
            [DynamicFormItemDefine("监控设备数量")]
            public string jksbsl { get; set; }
            [DynamicFormItemDefine("企业评级")]
            public string industry_type { get; set; }
            [DynamicFormItemDefine("经度")]
            public string lng { get; set; }
            [DynamicFormItemDefine("纬度")]
            public string lat { get; set; }
        }
    }
}
